
#include <stdlib.h>
#include <string.h>
#include "DBUtils.h"

/** Given an array of field name strings and an array of field types,
 * make an array of field names and types that can be used to create a
 * table.
 * 
 * @param dnames A NULL terminated string list of field names.
 * 
 * @param dtypes A NULL terminated string list of field types.
 * 
 * @return The synthesised string ready to be put into a table
 * creation SQL line. */
char *DBUtils::makeFieldDefinitions(const char **dnames, const char **dtypes)
{
   char *table_fields = NULL;
   int all_len, i, j;
   all_len = 0; i = 0; j = 0;
   all_len += (strlen("("));
   while ((dnames[i] != NULL) && (dtypes[i] != NULL))
   {
      all_len += (strlen(dnames[i]) + strlen(" "));
      all_len += (strlen(dtypes[i]) + strlen(", "));
      i++;
   }
   all_len += (strlen(")"));
   all_len += 1;
   table_fields = (char *)malloc(sizeof(char)*all_len);
   table_fields[0] = '\0';
   strcat(table_fields, "(");
   while ((dnames[j] != NULL) && (dtypes[j] != NULL))
   {
      strcat(table_fields, dnames[j]);
      strcat(table_fields, " ");
      strcat(table_fields, dtypes[j]);
      if (j < (i-1)) strcat(table_fields, ", ");
      j++;
   }
   strcat(table_fields, ")");
   return table_fields;
}

/** Takes a NULL terminated list of strings and builds a comma
 * separated list of the strings.
 * 
 * @param names The list of string to comma separate.
 * 
 * @return The returned string which is a comma separated list. */
char *DBUtils::makeCommaSeparatedList(const char **names)
{
   char *list = NULL;
   int all_len, i, j;
   all_len = 0; i = 0; j = 0;
   while (names[i] != NULL)
   {
      all_len += (strlen(names[i]) + strlen(","));
      i++;
   }
   all_len += 1;
   list = (char *)malloc(sizeof(char)*all_len);
   list[0] = '\0';
   while (names[j] != NULL)
   {
      strcat(list, names[j]);
      if (j < (i-1)) strcat(list, ",");
      j++;
   }
   return list;
}
